package com.hsl.housaileibot001.config;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * HTTP 请求性能监控拦截器
 * 记录请求响应时间，用于性能分析
 */
public class PerformanceInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(PerformanceInterceptor.class);

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        String method = request.method();

        long startTime = System.currentTimeMillis();
        long startNano = System.nanoTime();

        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            logger.error("请求失败 [{}] {} - 耗时: {}ms", method, url, duration, e);
            throw e;
        }

        long duration = System.currentTimeMillis() - startTime;
        long durationNano = System.nanoTime() - startNano;

        int code = response.code();
        String message = response.message();

        // 记录性能指标
        if (duration > 5000) {
            // 超过 5 秒的请求记录为 WARN
            logger.warn("慢请求 [{}] {} - 状态: {} - 耗时: {}ms ({}ms)", 
                    method, url, code, duration, durationNano / 1_000_000);
        } else if (duration > 1000) {
            // 超过 1 秒的请求记录为 INFO
            logger.info("请求完成 [{}] {} - 状态: {} - 耗时: {}ms", 
                    method, url, code, duration);
        } else {
            // 快速请求记录为 DEBUG
            logger.debug("快速请求 [{}] {} - 状态: {} - 耗时: {}ms", 
                    method, url, code, duration);
        }

        return response;
    }
}
